"use client";

import { getWheelApi, getWheelReceiveApi, WheelsType } from "@/api/cashWheel";
import Box from "@/components/Box";
import { WheelClient } from "@/components/Box/WheelModal";
import { Link } from "@/i18n/routing";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { server } from "@/utils/client";
import { copyText, timeFormat } from "@/utils/methods";
import { useCountDown } from "ahooks";
import { Popup, Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { createContext, FC, Fragment, useContext, useEffect, useState } from "react";
import LotteryWheel from "./LotteryWheel";
import styles from "./style.module.scss";
interface Props {
    // wheel: WheelsType;
    allHistory: any[];
    phones: any[];
}
interface ContextType extends WheelsType, Props {
    handler: () => void;
}
const WheelContext = createContext<Partial<ContextType>>({});

const CashMainCom = () => {
    return (
        <div className={`${styles.cashMain} ${styles.cashMain} ${styles.type1}`}>
            <div className={styles.haveCash}>
                <img src="/wheel/cash.png" alt="" className={styles.cashImg} />
                <div>
                    {" "}
                    R$ <span className={styles.cash}>94.15</span>
                </div>
                <span className={styles.withdraw}>
                    <img src="/wheel/pix.png" alt="" /> SACAR{" "}
                </span>
            </div>
            <div className={styles.progress}>
                <div className={styles.num}> 94.15%</div>
                <div className={styles.bar}>
                    <span style={{ width: "calc(97.15% - 0.07rem)" }}></span>
                </div>
            </div>
            <div className={styles.needCash}>
                {" "}
                Ainda e necessário <span className={styles.needCashNum}>5.85</span> para realizar do
                saque{" "}
            </div>
        </div>
    );
};
const DrawMain1 = () => {
    return (
        <div className={styles.drawMain}>
            <div className={styles.draw}>
                {/*<img src="/wheel/d.png" className={styles.lamp} />*/}
                {/*<img src="/wheel/light1.png" className={styles.light1} />*/}
                {/*<img src="/wheel/light2.png" className={styles.light2} />*/}
                {/*<div className={styles.pointer}>*/}
                {/*    <img src="/wheel/pointer.png" />*/}
                {/*</div>*/}
                {/*<img src="/wheel/bg_light.png" className={styles.drawBgImg} />*/}
                {/*<div className={`${styles.drawLen} ${styles.position} `}></div>*/}

                {/* <div className={styles.drawContents}>
          <canvas id={styles.draw} width={306} height={306} />
        </div> */}
                <LotteryWheel />
            </div>
        </div>
    );
};
const DrawContent = () => {
    return (
        <div className={styles.drawContent}>
            <div className={styles.text}>
                <span>
                    <span style={{ color: "rgb(135, 149, 177)" }}>Expira em</span> 2d 19:18:13
                </span>
            </div>
            <div className={styles.cashButton}>
                <div> Convide amigos para ajudar com saques</div>
                <div className={`${styles.iconfont} ${styles.iconShare}`}></div>
            </div>
        </div>
    );
};
type Dtltype = "left" | "right";
const LeftListClient = () => {
    const wheel = useContext(WheelContext);
    return (
        <>
            <div className={`${styles.winList} ${styles.swipernoswiping} ${styles.type2}`}>
                {wheel.allHistory &&
                    wheel.allHistory.length > 0 &&
                    wheel.allHistory?.map((item, index) => {
                        return (
                            <div className={styles.item} key={index}>
                                <span className={`${styles.name} ${styles.omitWrap}`}>
                                    {item.phone_number}
                                </span>
                                <span className={styles.tipText}>
                                    {timeFormat(item.receive_time, "br", undefined, true)}
                                </span>
                                <div className={styles.value}>
                                    <span className={styles.addCash}>+100</span>
                                    <span className={styles.unit}> R$</span>
                                </div>
                            </div>
                        );
                    })}
            </div>
        </>
    );
};
const getSelfHistoryApi = () => {
    return server.request<any[]>({
        url: "/v1/api/user/turntable/self_receive",
        method: "POST",
    });
};
const RightListClient = () => {
    const [selfHistory, setSelfHistory] = useState<any[]>([]);

    useEffect(() => {
        getSelfHistoryApi().then((res) => {
            setSelfHistory(res.data);
        });
    }, []);
    return (
        <div className={"h-[100%] overflow-scroll p-[10px]"}>
            <div
                className={
                    "grid grid-cols-[1.3889rem_1fr_0.6944rem] gap-y-[0.1389rem] text-[0.0972rem]" +
                    " text-[#8795b1]"
                }
            >
                {selfHistory.map((item, index) => {
                    return (
                        <Fragment key={index}>
                            <div className={"flex"}>
                                <span className={"mr-[0.0694rem] text-[0.12rem] text-[#6ddf39]"}>
                                    +{item.lose_amount}
                                </span>
                                <div
                                    className={
                                        "h-[0.16rem] w-[0.16rem] rounded-[50%] bg-[#6ddf39] text-center" +
                                        " text-[0.07rem] leading-[0.16rem] text-[#fff]"
                                    }
                                >
                                    R$
                                </div>
                            </div>
                            <div className={"flex flex-1"}>
                                {" "}
                                {timeFormat(item.receive_time, "br", undefined)}
                            </div>
                            <div className={"flex items-center justify-end text-[#f0ae18]"}>
                                <Image
                                    className={"mr-[0.0694rem] object-contain"}
                                    src={"/wheels/group.png"}
                                    alt={"group"}
                                    width={20}
                                    height={8}
                                />
                                <span>+{item.count_person}</span>
                            </div>
                        </Fragment>
                    );
                })}
            </div>
        </div>
    );
};
const Report = () => {
    const [activeTab, setActiveTab] = useState<Dtltype>("left");

    const handler = (dtl: Dtltype) => {
        setActiveTab(dtl);
    };
    const activeClass = clsx(
        styles.vanTabItem,
        activeTab === "left" ? styles.vanTabAcriveLeft : styles.vanTabAcriveRight
    );

    return (
        <div className={styles.report}>
            <div className={`${styles.vanTabs} ${styles.vanTabsLine}`}>
                <div className={styles.vanTabsWrap}>
                    <div className={styles.vanTabsNav}>
                        <div
                            className={`${styles.vanTabItem} ${activeTab === "right" ? styles.vanTabAcriveRight : ""} `}
                            onClick={() => handler("left")}
                        >
                            <span className={activeTab === "left" ? styles.activeText : ""}>
                                Relatório
                            </span>
                        </div>
                        <div
                            className={`${styles.vanTabItem} ${activeTab === "left" ? styles.vanTabAcriveLeft : ""}`}
                            onClick={() => handler("right")}
                        >
                            <span className={activeTab === "right" ? styles.activeText : ""}>
                                Minha Referencia
                            </span>
                        </div>
                    </div>
                </div>
                <div className={styles.vanTabsContent}>
                    <div className={styles.vantabpane}>
                        <div className={styles.tabContent}>
                            {activeTab === "left" ? <LeftListClient /> : <RightListClient />}
                        </div>
                    </div>
                </div>
            </div>
            <div className={styles.rules}>
                <h2>Regras</h2>
                <ul className={styles.tipsContent}>
                    <li>1.Você pode iniciar um saque quando o valor acumulado atingir 100 BRL. </li>
                    <li>
                        2.Convidar amigos para se registrarem no 9f.com irá ajudá- lo a sacar
                        dinheiro rapidamente.
                    </li>
                    <li>3. Cada usuário receberá uma única rodada grátis por dia. </li>
                    <li>
                        4.Cada usuário tem um período de validade de 3 dias para cada atividade e
                        pode participar da atividade várias vezes.
                    </li>
                    <li>
                        5.Se você receber um bônus de dinheiro extra, pode jogar jogos de graça e
                        ganhar ainda mais dinheiro real.
                    </li>
                    <li>6.Se voce nao retirar o dinheiro dentro de 3 dias,ele ser perdido.</li>
                </ul>
            </div>
        </div>
    );
};
const WheelWallet = () => {
    const user = useUserInfoStore((state) => state.userInfo);
    const wheel = useContext(WheelContext);
    return (
        <Box className={"w-[100%]"}>
            <div
                className={
                    "relative h-[1.6389rem] w-[100%] " +
                    " flex flex-col bg-[url(/wheels/wheel-wallet.png)]" +
                    " bg-[length:100%_100%]"
                }
            >
                <div className={"flex-1 p-[0.1389rem]"}>
                    <div className={"text-[#49c25a]"}>
                        <span className={"iconfont icon-yonghu"}></span>
                        <span>Conta</span>
                        <span>{user.user_phone}</span>
                    </div>
                    <div className={"text-[0.4861rem] font-bold text-[#008213]"}>
                        R$ <span>{wheel.activate?.amount || 0}</span>
                    </div>
                </div>
                <div
                    className={
                        "flex h-[0.4167rem] w-[100%] items-center justify-center text-center text-[0.125rem] font-bold"
                    }
                >
                    <span className={"mr-[10px] text-[#008213]"}>Faltam para O saque</span>
                    <span className={"text-[#eef100]"}>
                        R${(wheel.num! - wheel.activate?.amount! || 0).toFixed(2)}
                    </span>
                </div>
                {/*top*/}
            </div>
        </Box>
    );
};

const DrawMain = () => {
    const wheel = useContext(WheelContext);

    return (
        <div className={"relative"}>
            <WheelWallet />

            <div className={"-mt-[0.2083rem] transform"}>
                <WheelClient isRotate={true} wheel={wheel} onRotateEnd={wheel.handler!} />
            </div>
        </div>
    );
};
const CountdownClient = () => {
    const wheel = useContext(WheelContext);

    const [_, formattedRes] = useCountDown({
        leftTime: wheel.activate?.end_time! * 1000 - Date.now(),
    });
    const { days, hours, minutes, seconds } = formattedRes;
    const receiveHandler = () => {
        getWheelReceiveApi({ unique_id: wheel.not_receive![0].unique_id }).then((res) => {
            wheel.handler && wheel.handler();
        });
    };
    return (
        <div className={"relative flex justify-center"}>
            {wheel.not_receive && wheel.not_receive.length > 0 ? (
                <div className={"mt-[10px]"}>
                    <Image
                        src={"/wheels/receive-button.png"}
                        alt={"receive"}
                        height={80}
                        width={160}
                        onClick={receiveHandler}
                    ></Image>
                </div>
            ) : (
                <>
                    <img src="/wheels/countdown-bg.png" alt="" />
                    <span className={"absolute bottom-[50%] ml-[0.2083rem] translate-y-1/2"}>
                        {String(days).padStart(2, "0")}:{String(hours).padStart(2, "0")}:
                        {String(minutes).padStart(2, "0")}:{String(seconds).padStart(2, "0")}
                    </span>
                </>
            )}
        </div>
    );
};
const phones = Array(9)
    .fill(0)
    .map((_, i) => {
        const num = `557894567${Math.floor(Math.random() * 1000)
            .toString()
            .padStart(4, "0")}`;
        return num;
    });
const ShareClient = () => {
    const [visible, setVisible] = useState(false);
    const wheel = useContext(WheelContext);
    const user = useUserInfoStore((state) => state.userInfo);

    const [currentPhoneIndex, setCurrentPhoneIndex] = useState(0);

    const shareUrl = `${process.env.NEXT_PUBLIC_SHARE_URL}/br/sharecwbr?turntable=${wheel.activities && wheel.activities[0].id}&user=${user.id}&time=${wheel.activate?.end_time}`;
    const url = encodeURIComponent(`${shareUrl}`);
    const text = encodeURIComponent(`Receba 100 BRL de graça,Pix SAQUE RÁPIDO`);
    const t = useTranslations();
    const SHARE_SOURCE = [
        {
            icon: "/summary/Facebook.png",
            label: "Facebook",
            shareUrl: `https://www.facebook.com/sharer/sharer.php?u=${url}&t=${text}`,
        },
        {
            icon: "/summary/WhatsApp.png",
            label: "WhatsApp",
            shareUrl: `https://api.whatsapp.com/send?text=${text}`,
        },
        {
            icon: "/summary/Telegram.png",
            label: "Telegram",
            shareUrl: `https://t.me/share/url?url=${url}&text=${text}`,
        },
        {
            icon: "/summary/Twitter.png",
            label: "Twitter",
            shareUrl: `https://twitter.com/intent/tweet?text=${text}`,
        },
        {
            icon: "/summary/Email.png",
            label: "Email",
            shareUrl: `mailto: ?&subject=&cc=&bcc=&body=${url}%0A${text}`,
        },
    ];

    const copy = (text: string) => {
        copyText(text);
        Toast.show({ icon: "success", content: t("SummaryPage.copySuc"), maskClickable: false });
    };
    const handler = () => {
        const current = wheel.phones?.[currentPhoneIndex];
        window.open(`https://wa.me/${current}`);
        setCurrentPhoneIndex((value) => (value += 1));
    };

    return (
        <>
            <div className={"p-[0.1389rem]"}>
                <div
                    className={
                        "rounded-[0.1111rem] bg-gradient-to-b from-[#84ea24_20%] to-[#1b781a]" +
                        " h-[0.4861rem]"
                    }
                >
                    <div className={"flex h-[100%] p-[0.0694rem]"}>
                        <div
                            className={
                                "flex-1 rounded-[0.0694rem] bg-[rgba(255,255,255,0.5)]" +
                                " flex items-center pl-[0.0694rem]"
                            }
                        >
                            <span className={""}>Compartilhe mais, saque mais rápido.</span>
                        </div>
                        <div
                            className={"flex w-[0.4167rem] items-center pl-[0.0694rem]"}
                            onClick={() => setVisible(true)}
                        >
                            <Image src={"/wheels/share.png"} alt={"share"} width={30} height={30} />
                        </div>
                    </div>
                </div>
            </div>

            <Popup
                visible={visible}
                getContainer={null}
                onMaskClick={() => {
                    setVisible(false);
                }}
                onClose={() => {
                    setVisible(false);
                }}
                showCloseButton
                bodyStyle={{ background: "#fff" }}
            >
                <div className={"p-[0.1389rem] text-[#555555]"}>
                    <h1>1.Convide amlgos para ajudar com saques</h1>
                    <div
                        className={"mt-[0.1389rem] grid grid-cols-5 justify-center gap-[0.1389rem]"}
                    >
                        {SHARE_SOURCE.map((source, index) => {
                            return (
                                <a
                                    href={source.shareUrl}
                                    key={index}
                                    target={"_blank"}
                                    className={"flex flex-col items-center"}
                                >
                                    <Image src={source.icon} alt={"Mais"} width={70} height={70} />
                                    <p className={"mt-[0.0347rem] text-[12px] text-[#808080]"}>
                                        {source.label}
                                    </p>
                                </a>
                            );
                        })}
                    </div>

                    <div className={"mt-[0.0694rem]"}>
                        <h1 className={"text-[14px]"}>
                            Compartilhe este link de indicação com seus amigos
                        </h1>
                        <div
                            className={
                                "rounded-[3px] bg-[#f9f9f9] p-[0.0694rem] text-[#808080]" +
                                " mt-[0.0347rem] flex items-center"
                            }
                        >
                            <span className={"mr-[0.0694rem] flex-1 truncate"}>{shareUrl}</span>
                            <span
                                id="copy"
                                className={"text-[#40a1de]"}
                                onClick={() => copy(shareUrl)}
                            >
                                {t("SummaryPage.Cópia")}
                            </span>
                        </div>
                    </div>

                    <div className={"mt-[0.0694rem]"}>
                        <h1>2.Enviar convite para jogador aleatório ajudar</h1>

                        <div className={"mt-[0.0694rem] bg-[#000] p-[10px]"}>
                            <div className={"grid grid-cols-3 gap-[5px] text-[0.0833rem]"}>
                                {wheel.phones?.map((phone, index) => {
                                    return (
                                        <span
                                            style={{
                                                color: index < currentPhoneIndex ? "#fff" : "#ccc",
                                            }}
                                            key={index}
                                        >
                                            {phone}
                                        </span>
                                    );
                                })}
                            </div>

                            <div
                                className={
                                    "grid grid-cols-2 gap-[0.1389rem] text-[0.12rem] text-[#fff]"
                                }
                            >
                                <div
                                    onClick={handler}
                                    className={
                                        "flex items-center rounded-[0.0694rem] bg-[#10cb8c]" +
                                        " p-[0.0694rem] text-[#fff]"
                                    }
                                >
                                    <div className={"flex-1"}>
                                        <p>Enviar Mensagem </p>
                                        <p>no WhatsAPP</p>
                                    </div>
                                    <Image
                                        src={"/summary/WhatsApp-nobg.png"}
                                        alt={"whatsApp"}
                                        width={40}
                                        height={40}
                                    />
                                </div>
                                <Link
                                    href={`sms:${wheel.phones?.join(";")}?body=message_body`}
                                    className={
                                        "flex items-center rounded-[10px] bg-[#35b2fe]" +
                                        " p-[0.0694rem] text-[#fff]"
                                    }
                                >
                                    <div className={"flex-1"}>
                                        <p>Enviar Mensagem </p>
                                        <p>SMS</p>
                                    </div>
                                    <Image
                                        src={"/summary/SMS.png"}
                                        alt={"whatsApp"}
                                        width={40}
                                        height={40}
                                    />
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>
            </Popup>
        </>
    );
};

const CashWheelClient: FC<Props> = (props) => {
    const getWheelData = async () => {
        return getWheelApi().then((res) => {
            if (res.code === 200) {
                setValues((staticValue) => {
                    return { ...staticValue, ...res.data };
                });
            }
            return res;
        });
    };

    const [values, setValues] = useState<Partial<ContextType>>({
        num: 100,
        allHistory: props.allHistory || [],
        phones: props.phones || [],
        handler: getWheelData,
    });
    useEffect(() => {
        getWheelData();
    }, []);

    return (
        <>
            <WheelContext.Provider value={values}>
                <DrawMain />
                {/*倒计时*/}
                <CountdownClient />
                {/*分享*/}
                {values.activate && values.activate?.end_time > 0 ? <ShareClient /> : null}
                <div className={styles.cashWheelClient}>
                    {/*<CashMainCom />*/}
                    {/*<DrawContent />*/}
                    <Report />
                    {/*<LotteryWheel />*/}
                </div>
            </WheelContext.Provider>
        </>
    );
};

export default CashWheelClient;
